package cn.ivicar.cloud.mqtt;

import javax.jms.ExceptionListener;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.jms.JMSException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.log4j.Logger;
import org.fusesource.mqtt.client.QoS;
import org.fusesource.mqtt.client.Topic;

public class MqttServlet extends GenericServlet implements ExceptionListener {
    private static Logger LOGGER = Logger.getLogger(MqttServlet.class);

    private static ExecutorService executorPool = Executors.newFixedThreadPool(2);

    @Override
    public void onException(JMSException e) {
        LOGGER.error(String.format("MQTT消息处理Servlet出现异常，错误消息：%s", e.getMessage()), e);
    }

    @Override
    public void init() throws ServletException {
        super.init();
        MqttClient.connect();
        try {
            executorPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        LOGGER.info("开始启动MQTT消息处理Servlet...");
                        Topic[] topics = { new Topic("ivicar_iov/#", QoS.EXACTLY_ONCE) };
                        MqttClient.processMessage(topics);
                    } catch (Exception e) {
                        System.out.println("处理MQTT消息发生未知异常" + e.toString());
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    @Override
    public void destroy() {
        MqttClient.tearDown();
    }
}
